# -*- coding: utf-8 -*-
import redis
import threading
from scrapy.utils.project import get_project_settings


class Redis(object):
    """
    Redis客户端简易封装
    """
    _instance_lock = threading.Lock()
    _biz_inited = False

    def __init__(self):
        if not self._biz_inited:
            self._biz_inited = True
            settings = get_project_settings()
            self.bot_name = settings.get('BOT_NAME')
            self.redis_host = settings.get('REDIS_HOST', 'localhost')
            self.redis_password = settings.get('REDIS_PASSWORD', '')
            self.redis_port = settings.get('REDIS_PORT', 6379)
            self.redis_db = settings.get('REDIS_DB', 0)
            self.pool = redis.ConnectionPool(host=self.redis_host, port=self.redis_port, password=self.redis_password)
            self.client = redis.Redis(connection_pool=self.pool)

    def __new__(cls, *args, **kwargs):
        if not hasattr(Redis, "_instance"):
            with Redis._instance_lock:
                if not hasattr(Redis, "_instance"):
                    Redis._instance = object.__new__(cls)
        return Redis._instance

    # 关闭链接
    def close(self):
        self.pool.disconnect()

    # 销毁关闭连接池
    def __del__(self):
        if self.pool:
            self.pool.disconnect()
